package com.fesine.netapply.controller;

import com.alibaba.fastjson.JSONObject;
import com.fesine.netapply.service.UserService;
import com.fesine.netapply.util.CryptographyUtil;
import com.fesine.netapply.util.PageUtil;
import com.fesine.netapply.util.ResponseUtil;
import com.fesine.netapply.util.StringUtil;
import com.fesine.netapply.vo.PageBean;
import com.fesine.netapply.vo.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.portlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Component
@RequestMapping({"/user"})
public class UserController {
    private static final Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    private String md5Salt="fesine";


    @RequestMapping({"/login"})
    public String login(User user, HttpServletRequest request) {
        String captchaToken = ((String) request.getSession().getAttribute("captchaToken")).toLowerCase();
        String checkCode = request.getParameter("checkCode").toLowerCase();
        logger.info("----->captchaToken:" + captchaToken + ",checkCode:" + checkCode);
        User resultUser = this.userService.login(md5User(user));
        if (!captchaToken.equals(checkCode.toLowerCase())) {
            request.setAttribute("user", user);
            request.setAttribute("errorMsg", "验证码错误！");
            return "login";
        } else {
            if (resultUser.getId() == null) {
                request.setAttribute("user", user);
                request.setAttribute("errorMsg", "用户名或密码错误！");
                return "login";
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("currentUser", resultUser);
                return "redirect:/main.jsp";
            }
        }
    }

    @RequestMapping({"/logout"})
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login.jsp";
    }

    @RequestMapping({"/list"})
    public ModelAndView list(@RequestParam(
            value = "page",
            required = false
    ) String page, User s_user, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        if (StringUtil.isEmpty(page)) {
            page = "1";
            session.setAttribute("s_user", s_user);
        } else {
            s_user = (User) session.getAttribute("s_user");
        }

        PageBean pageBean = new PageBean(Integer.parseInt(page), 3);
        List userList = (List) this.userService.find(pageBean, s_user);
        int total = this.userService.count(s_user);
        String pageCode = PageUtil.getPagation(request.getContextPath() + "/user/list.do", total,
                Integer.parseInt(page), 3);
        mav.addObject("pageCode", pageCode);
        mav.addObject("modeName", "用户管理");
        mav.addObject("userList", userList);
        mav.addObject("mainPage", "user/list.jsp");
        mav.setViewName("main");
        return mav;
    }


    @RequestMapping({"/save"})
    public String save(User user) {

        if (user.getId() == null) {
            this.userService.add(md5User(user));
        } else {
            this.userService.update(md5User(user));
        }

        return "redirect:/user/list.do";
    }

    @RequestMapping({"/delete"})
    public void delete(String id, HttpServletResponse response)
            throws Exception {
        userService.delete(Integer.valueOf(id).intValue());
        JSONObject result = new JSONObject();
        result.put("success", Boolean.valueOf(true));
        ResponseUtil.write(result, response);
    }


    /**
     * 新增用户和修改用户信息时，密码需要加密
     * @param user
     * @return 加密后的用户
     */
    private User md5User(User user) {
        String password = user.getPassword();
        logger.info("------->密码:"+ password+",salt:"+ md5Salt);
        user.setPassword(CryptographyUtil.md5(password, md5Salt));
        return user;
    }

}
